<template>
  <div class="product-tag-manage">
    <div class="header">
      <h2>商品标签管理</h2>
      <button class="add-btn" @click="openAddDialog">+ 新增商品标签</button>
    </div>
    <div class="tag-list">
      <div v-for="tag in tags" :key="tag.id" class="tag-card">
        <div class="tag-icon" :style="{ background: tag.color }">
          <img v-if="isImageIcon(tag.icon)" :src="tag.icon" class="icon-img" />
          <component v-else :is="tag.icon" class="icon-svg" />
        </div>
        <div class="tag-name">{{ tag.name }}</div>
        <div class="tag-desc">{{ tag.description }}</div>
        <div class="tag-keywords" v-if="tag.keywords && tag.keywords.length > 0">
          <div class="keywords-label">关键词：</div>
          <div class="keywords-tags">
            <span v-for="keyword in tag.keywords" :key="keyword" class="keyword-chip">
              {{ keyword }}
            </span>
          </div>
        </div>
        <div class="tag-actions">
          <button @click="openEditDialog(tag)">编辑</button>
          <button class="danger" @click="confirmDelete(tag)">删除</button>
        </div>
      </div>
    </div>
    <!-- 新增/编辑弹窗 -->
    <div v-if="dialogVisible" class="dialog-mask">
      <div class="dialog">
        <div class="dialog-title">
          {{ dialogMode === 'add' ? '新增商品标签' : '编辑商品标签' }}
          <span class="close" @click="closeDialog">×</span>
        </div>
        <div class="dialog-body">
          <div class="form-item">
            <label>标签名称</label>
            <input v-model="form.name" placeholder="请输入标签名称" />
          </div>
          <div class="form-item">
            <label>标签图标</label>
            <div class="icon-select">
              <!-- 上传图片按钮 -->
              <span class="icon-option upload-option">
                <input type="file" accept="image/*" class="upload-input" @change="onIconUpload" />
                <span class="upload-text">+</span>
              </span>
              <!-- 已上传图片预览 -->
              <span v-if="isImageIcon(form.icon)" class="icon-option active" @click="form.icon = iconList[0]" title="点击切换回默认图标">
                <img :src="form.icon" class="icon-img" />
              </span>
              <!-- 内置SVG图标选择 -->
              <span v-for="icon in iconList" :key="icon" :class="['icon-option', form.icon === icon ? 'active' : '']" @click="form.icon = icon">
                <component :is="icon" class="icon-svg" />
              </span>
            </div>
          </div>
          <div class="form-item">
            <label>标签颜色</label>
            <input type="color" v-model="form.color" class="color-picker" />
            <span class="color-value">{{ form.color }}</span>
          </div>
          <div class="form-item">
            <label>标签简介</label>
            <textarea v-model="form.description" placeholder="请输入标签简介"></textarea>
          </div>
          <div class="form-item">
            <label>关联关键词</label>
            <div class="keywords-container">
              <div class="keyword-input">
                <input 
                  v-model="newKeyword" 
                  placeholder="输入关键词，多个关键词用逗号分隔，如：易碎,玻璃,陶瓷"
                  @keyup.enter="addKeywords"
                />
                <button type="button" @click="addKeywords" class="add-keyword-btn">添加</button>
              </div>
              <div class="keywords-list" v-if="form.keywords.length > 0">
                <div v-for="keyword in form.keywords" :key="keyword" class="keyword-tag">
                  <span>{{ keyword }}</span>
                  <button @click="removeKeyword(keyword)" class="remove-keyword-btn">×</button>
                </div>
              </div>
              <div class="keywords-tip">关键词用于商品自动标签匹配，支持多个关键词，用逗号分隔</div>
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="closeDialog">取消</button>
          <button class="primary" @click="saveTag">保存</button>
        </div>
      </div>
    </div>
    <!-- 删除确认弹窗 -->
    <div v-if="deleteDialogVisible" class="dialog-mask">
      <div class="dialog">
        <div class="dialog-title">确认删除</div>
        <div class="dialog-body">确定要删除标签“{{ deleteTarget?.name }}”吗？</div>
        <div class="dialog-footer">
          <button @click="deleteDialogVisible = false">取消</button>
          <button class="danger" @click="deleteTag">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, markRaw } from 'vue'
// 假设有3个本地SVG图标组件
import TagIcon1 from '@/assets/tag-icons/TagIcon1.vue'
import TagIcon2 from '@/assets/tag-icons/TagIcon2.vue'
import TagIcon3 from '@/assets/tag-icons/TagIcon3.vue'

const iconList = [TagIcon1, TagIcon2, TagIcon3]
const colorList = [
  '#DBEAFE', '#FDE2E4', '#FDF6B2', '#CFFAFE', '#F3E8FF',
  '#E0E7FF', '#F1F5F9', '#FEF9C3', '#FDE68A', '#D1FAE5'
]

interface TagItem {
  id: number
  name: string
  icon: any // 可以是组件或图片URL
  color: string
  description: string
  keywords: string[] // 关联关键词
}

const tags = ref<TagItem[]>([
  { id: 1, name: '易碎品', icon: TagIcon1, color: '#DBEAFE', description: '需要小心搬运的商品', keywords: ['易碎', '玻璃', '陶瓷', '小心搬运'] },
  { id: 2, name: '含电池', icon: TagIcon2, color: '#FDE2E4', description: '含有电池的商品，运输需注意', keywords: ['电池', '充电宝', '锂电池', '危险品'] },
  { id: 3, name: '日系', icon: TagIcon3, color: '#FDF6B2', description: '日本风格商品', keywords: ['日系', '日本', '动漫', '二次元'] },
])

const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const form = reactive({
  id: 0,
  name: '',
  icon: iconList[0],
  color: colorList[0],
  description: '',
  keywords: [] as string[]
})

function openAddDialog() {
  dialogMode.value = 'add'
  Object.assign(form, { id: 0, name: '', icon: iconList[0], color: colorList[0], description: '', keywords: [] })
  dialogVisible.value = true
}
function openEditDialog(tag: TagItem) {
  dialogMode.value = 'edit'
  Object.assign(form, { ...tag, keywords: [...tag.keywords] })
  dialogVisible.value = true
}
function closeDialog() {
  dialogVisible.value = false
}
function saveTag() {
  if (!form.name) return alert('请输入标签名称')
  if (!form.icon) return alert('请选择标签图标')
  if (!form.color) return alert('请选择标签颜色')
  if (dialogMode.value === 'add') {
    tags.value.push({
      id: Date.now(),
      name: form.name,
      icon: form.icon,
      color: form.color,
      description: form.description,
      keywords: [...form.keywords]
    })
  } else {
    const idx = tags.value.findIndex(t => t.id === form.id)
    if (idx > -1) {
      tags.value[idx] = { 
        ...form,
        keywords: [...form.keywords]
      }
    }
  }
  dialogVisible.value = false
}

// 关键词管理相关函数
const newKeyword = ref('')
function addKeywords() {
  if (!newKeyword.value.trim()) return
  
  // 按逗号分割关键词
  const keywords = newKeyword.value.split(',').map(k => k.trim()).filter(k => k)
  
  if (keywords.length === 0) return
  
  // 检查重复关键词
  const newKeywords = keywords.filter(keyword => !form.keywords.includes(keyword))
  
  if (newKeywords.length === 0) {
    alert('所有关键词都已存在')
    return
  }
  
  // 添加新关键词
  form.keywords.push(...newKeywords)
  newKeyword.value = ''
}

function removeKeyword(keyword: string) {
  const index = form.keywords.indexOf(keyword)
  if (index > -1) {
    form.keywords.splice(index, 1)
  }
}

const deleteDialogVisible = ref(false)
const deleteTarget = ref<TagItem | null>(null)
function confirmDelete(tag: TagItem) {
  deleteTarget.value = tag
  deleteDialogVisible.value = true
}
function deleteTag() {
  if (deleteTarget.value) {
    tags.value = tags.value.filter(t => t.id !== deleteTarget.value!.id)
  }
  deleteDialogVisible.value = false
}

function isImageIcon(icon: any) {
  return typeof icon === 'string' && (icon.startsWith('data:image') || icon.startsWith('blob:') || icon.startsWith('http'))
}
function onIconUpload(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  if (!file.type.startsWith('image/')) return alert('请选择图片文件')
  if (file.size > 1024 * 1024) return alert('图片不能超过1MB')
  const reader = new FileReader()
  reader.onload = (ev) => {
    form.icon = ev.target?.result as string
  }
  reader.readAsDataURL(file)
}
</script>

<style scoped>
.product-tag-manage {
  padding: 32px;
  background: #f7f9fb;
  min-height: 100vh;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}
.add-btn {
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 8px 20px;
  font-size: 16px;
  cursor: pointer;
}
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}
.tag-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px #e5e7eb;
  width: 220px;
  padding: 24px 20px 16px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.tag-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}
.icon-svg {
  width: 28px;
  height: 28px;
}
.icon-img {
  width: 28px;
  height: 28px;
  object-fit: contain;
}
.tag-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 6px;
}
.tag-desc {
  color: #6b7280;
  font-size: 14px;
  min-height: 32px;
  margin-bottom: 16px;
  text-align: center;
}
.tag-actions {
  display: flex;
  gap: 12px;
}
.tag-actions button {
  background: #f3f4f6;
  border: none;
  border-radius: 6px;
  padding: 6px 16px;
  cursor: pointer;
  font-size: 15px;
  display: flex;
  align-items: center;
}
.tag-actions .danger {
  color: #ef4444;
  background: #fff1f2;
}
.dialog-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.dialog {
  background: #fff;
  border-radius: 16px;
  min-width: 420px;
  max-width: 90vw;
  box-shadow: 0 4px 32px #dbeafe;
  padding-bottom: 16px;
}
.dialog-title {
  font-size: 20px;
  font-weight: 600;
  padding: 20px 24px 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dialog-title .close {
  font-size: 26px;
  cursor: pointer;
  color: #9ca3af;
}
.dialog-body {
  padding: 16px 24px 0 24px;
}
.form-item {
  margin-bottom: 18px;
}
.form-item label {
  display: block;
  font-size: 15px;
  margin-bottom: 6px;
  color: #374151;
}
.icon-select {
  display: flex;
  gap: 12px;
}
.icon-option {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid transparent;
  cursor: pointer;
  background: #f3f4f6;
}
.icon-option.active {
  border-color: #2563eb;
  background: #e0e7ff;
}
.color-select {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.color-option {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  border: 2px solid transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.color-option.active {
  border-color: #2563eb;
}
.color-checked {
  color: #2563eb;
  font-size: 18px;
  font-weight: bold;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 16px 24px 0 24px;
}
.dialog-footer .primary {
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 8px 24px;
  font-size: 16px;
  cursor: pointer;
}
.dialog-footer .danger {
  background: #fff1f2;
  color: #ef4444;
  border: none;
  border-radius: 6px;
  padding: 8px 24px;
  font-size: 16px;
  cursor: pointer;
}
.icon-option.upload-option {
  border: 2px dashed #a5b4fc;
  background: #f3f4f6;
  color: #2563eb;
  position: relative;
  overflow: hidden;
  justify-content: center;
}
.upload-input {
  position: absolute;
  left: 0; top: 0; width: 100%; height: 100%;
  opacity: 0;
  cursor: pointer;
  z-index: 1;
}
.upload-text {
  font-size: 22px;
  font-weight: bold;
  color: #2563eb;
}
.icon-img {
  width: 28px;
  height: 28px;
  object-fit: contain;
  border-radius: 6px;
}
.color-picker {
  width: 40px;
  height: 32px;
  border: none;
  background: none;
  vertical-align: middle;
  margin-right: 10px;
}

/* 关键词相关样式 */
.keywords-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.keyword-input {
  display: flex;
  gap: 8px;
  align-items: center;
}

.keyword-input input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.add-keyword-btn {
  padding: 8px 16px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.keywords-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.keyword-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: #f3f4f6;
  border-radius: 4px;
  font-size: 12px;
}

.remove-keyword-btn {
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-keyword-btn:hover {
  color: #ef4444;
}

.keywords-tip {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

/* 标签卡片中的关键词显示 */
.tag-keywords {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f3f4f6;
}

.keywords-label {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 4px;
}

.keywords-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.keyword-chip {
  padding: 2px 6px;
  background: #e0e7ff;
  color: #3730a3;
  border-radius: 3px;
  font-size: 11px;
  white-space: nowrap;
}
.color-value {
  font-size: 15px;
  color: #374151;
  vertical-align: middle;
}
</style> 